﻿using Microsoft.AspNetCore.Http;
using NetCore.Attach.Model;
using System.IO;
using System.Collections.Generic;
using System.Linq;
namespace NetCore.Attach.BLL
{
    public class ApiService:SerivceBase,IApiService
    {
      
       
        public static string TempPath
        {
            get
            {
                return ApplicationEnvironments.RootPath + ApplicationEnvironments.TempPath;
            }
        }
        public static string PublicPath
        {
            get
            {
                return ApplicationEnvironments.Site.ConfigFile.publicPath;
            }
        }

        public AjaxResult Upload(IFormFile file,string fileName,string typeno)
        {
            if (file != null)
            {
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = file.FileName;
                }
               var attachType=  this.GetById<AttachTypeEntity>(typeno);
                string filePath = "";
                string fileType = Path.GetExtension(fileName);
                if (!string.IsNullOrWhiteSpace(attachType.FileTypeExts))
                {
                    var arrType = attachType.FileTypeExts.ToLower().Split(new char[] { ';',','});
                    if (!arrType.Contains(fileType.ToLower()))
                    {
                        return AjaxResult.Error("文件类型错误");
                    }
                }
                if (attachType != null)
                {
                    filePath = PublicPath;
                    if (attachType.IsTemp)
                    {
                        filePath = TempPath;
                    }
                    if (attachType.IsUserNo)
                    {
                        filePath += ApplicationEnvironments.DefaultSession.UserId + "/";
                    }
                    filePath += attachType.DirName + "/";
                    fileName = MyGenerateHelper.GenerateOrder() + Path.GetExtension(fileName);
                    
                    if (attachType.DirName.ToLower().Equals("avatar"))//头像
                    {
                        fileName = ApplicationEnvironments.DefaultSession.UserId + ".jpg";
                        FileInfo uinfo = new FileInfo(ApplicationEnvironments.RootPath + filePath + fileName);
                        if (uinfo.Exists)
                        {
                            if (!Directory.Exists(ApplicationEnvironments.RootPath + filePath + ApplicationEnvironments.DefaultSession.UserId + "/"))
                            {
                                Directory.CreateDirectory(ApplicationEnvironments.RootPath + filePath + ApplicationEnvironments.DefaultSession.UserId + "/");
                            }
                          
                            uinfo.MoveTo(ApplicationEnvironments.RootPath + filePath + ApplicationEnvironments.DefaultSession.UserId + "/" + MyGenerateHelper.GenerateOrder() + ".jpg");
                        }
                    }
                }
                else
                {
                    return AjaxResult.Error("参数错误");
                }
                filePath += fileName;
                FileInfo info = new FileInfo(ApplicationEnvironments.RootPath + filePath );
                if (!info.Exists)
                {
                    if (!info.Directory.Exists)
                    {
                        info.Directory.Create();
                    }
                }
                using (FileStream fs = System.IO.File.Create(ApplicationEnvironments.RootPath + filePath))
                {
                    file.CopyTo(fs);
                    fs.Flush();
                }
                return AjaxResult.Success(ApplicationEnvironments.Site.StaticBrower + filePath,"");
            }
            return AjaxResult.Error("文件错误");
        }

        public byte[] GetUserAvatar(string userid)
        {
            string filePath = PublicPath;
            var attachType = this.GetById<AttachTypeEntity>("AT0001");
            byte[] buffer = null;
            filePath += "avatar/" ;
            FileInfo uinfo = new FileInfo(ApplicationEnvironments.RootPath + filePath + userid + ".jpg");
            if (uinfo.Exists)
            {
                FileHelper.ReadFile(uinfo.FullName, out buffer);
            }
            if (buffer == null)
            {
                FileHelper.ReadFile(ApplicationEnvironments.RootPath + PublicPath + "/avatar/avatar.jpg", out buffer);
            }
            return buffer;
        }

        /// <summary>
        /// 获取文件夹
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public List<StaticFile> GetFolders(string parent)
        {
            string filePath = parent;
            List<StaticFile> valuePairs = new List<StaticFile>();
            if ( parent.Equals("#"))
            {
                filePath = "/";
                valuePairs.Add(new StaticFile {
                    id=filePath,
                    text="根目录",
                    parent="#",
                    icon="fa fa-tree",
                    children=true
                });
                return valuePairs;
            }
            DirectoryInfo info = new DirectoryInfo(ApplicationEnvironments.RootPath + filePath.Replace("//","/"));
            if (info.Exists)
            {
               var dirs=  info.GetDirectories();
                if (dirs != null && dirs.Length > 0)
                {
                    foreach (var item in dirs)
                    {
                        valuePairs.Add(new StaticFile
                        {
                            id = filePath+ item.Name+"/",
                            text = item.Name,
                            parent = parent,
                            icon = "fa fa-folder",
                            children = true
                        });
                    }
                }
            }
            return valuePairs;
        }

        /// <summary>
        /// 获取文件
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public List<StaticFile> GetFiles(string filePath)
        {
            List<StaticFile> valuePairs =new List<StaticFile>();
            if (string.IsNullOrWhiteSpace(filePath))
            {
                filePath = "upload/";
            }
            DirectoryInfo info = new DirectoryInfo(ApplicationEnvironments.RootPath + filePath);
            if (info.Exists)
            {
                var files = info.GetFiles();
                if (files != null && files.Length > 0)
                {
                    foreach (var file in files)
                    {
                        var fileStatic = new StaticFile
                        {
                            EditTime = file.LastWriteTime,
                            id = filePath + file.Name,
                            text = file.Name,
                            icon = "",
                            FileType = Path.GetExtension(file.Name),
                            HttpPath=ApplicationEnvironments.Site.StaticBrower+filePath + file.Name
                        };
                        this.GetFileIcon(ref fileStatic);
                        valuePairs.Add(fileStatic);
                    }
                }
            }
            return valuePairs;
        }

        private void GetFileIcon(ref StaticFile file)
        {
            string fileType = file.FileType.ToLower();
            switch (fileType)
            {
                case ".jpg":
                case ".jpeg":
                case ".png":
                case ".bmp":
                case ".gif":
                    file.IsImage = true;
                    file.icon = ApplicationEnvironments.Site.StaticBrower + file.id;
                    break;
                case ".xls":
                case ".xlsx":
                    file.icon = "fa-bar-chart-o";
                    break;
                case ".mp3":
                case ".mp4":
                    file.icon = "fa-music";
                    break;
                case ".mpg4":
                    file.icon = "fa-film";
                    break;
                default:
                    file.icon= "fa-file";
                    break;
            }
        }

        public bool FileDelete(string filePath) {
            if (File.Exists(ApplicationEnvironments.RootPath + filePath))
            {
                File.Delete(ApplicationEnvironments.RootPath + filePath);
            }
            return true;
        }
        /// <summary>
        /// 文件夹删除
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="strError"></param>
        /// <returns></returns>
        public bool FolderDelete(string folder,ref string strError)
        {
            DirectoryInfo info = new DirectoryInfo(ApplicationEnvironments.RootPath + folder);
            if (info.Exists)
            {
                var files = info.GetFiles();
                if (files != null && files.Length > 0)
                {
                    strError = "文件夹目录下还存在(" + files.Length+")个文件，无法删除";
                    return false;
                }
                info.Delete(false);
            }
            return true;
        }
    }
}
